package io.renren.common.utils.aliauth;

import lombok.extern.slf4j.Slf4j;

import com.alipay.api.AlipayApiException;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipaySystemOauthTokenRequest;
import com.alipay.api.response.AlipaySystemOauthTokenResponse;

@Slf4j
public class AliPayToken {
	/**
     * 获取支付宝付款人Userid
     * @param payOrder
     * @return
     */
    public static String doAliPayToken(String auth_code,String appid,String accountprivatekey,String alipaypublickey) {
    	String logPrefix = "【支付宝获取UserId】";
        AlipayConfig alipayConfig = new AlipayConfig();
        //alipayConfig.setAlipayAccount(alipayaccount);
    	alipayConfig.setAppId(appid);
    	alipayConfig.setPrivateKey(accountprivatekey);
    	alipayConfig.setAlipayPublicKey(alipaypublickey);
    	alipayConfig.setReqUrl("https://openapi.alipay.com/gateway.do");
    	AlipayClient client = new DefaultAlipayClient(alipayConfig.getReqUrl(), alipayConfig.getAppId(), alipayConfig.getPrivateKey(), AlipayConfig.FORMAT, AlipayConfig.CHARSET, alipayConfig.getAlipayPublicKey(), AlipayConfig.SIGNTYPE);
    	AlipaySystemOauthTokenRequest request = new AlipaySystemOauthTokenRequest();
    	request.setGrantType("authorization_code");
    	request.setCode(auth_code);
    	try {
			AlipaySystemOauthTokenResponse response = client.execute(request);
			log.info("{}：body={}", logPrefix, response.getBody());
			if(response.isSuccess()) {
				System.err.println("当前用户的userid:"+response.getUserId());
				return response.getUserId();
			}
		} catch (AlipayApiException e) {
			
		}
    	System.err.println("未获取到当前用户的userid");
    	return null;
    }
}
